#include "head.h"

#define FIFO_NAME "./fifo_test"

int EpollAddFd( int EpollFd, int SockFd, uint32_t Event )
{
    struct epoll_event EpollEvent;
    EpollEvent.events = Event;
    EpollEvent.data.fd = SockFd;

    int Ret = epoll_ctl( EpollFd, EPOLL_CTL_ADD, SockFd, &EpollEvent );
    if( -1 == Ret )
    {
        perror( "fail epoll_ctl" );
        return -1;
    }

    return 0;
}

int main(int argc, char const *argv[])
{
    mkfifo( FIFO_NAME, 0777 );
    int FifoFd = open( FIFO_NAME, O_RDONLY );
    if( -1 == FifoFd )
    {
        perror( "fail open fifo" );
        return -1;
    }

    int EpollFd = epoll_create( 2 );
    if ( -1 == EpollFd )
    {
        perror( "fail epoll_create" );
        return -1;
    }

    EpollAddFd( EpollFd, 0,      EPOLLIN );
    EpollAddFd( EpollFd, FifoFd, EPOLLIN );

    struct epoll_event EpollEventArray[2];

    while (1)
    {
        int Counter = epoll_wait( EpollFd, EpollEventArray, 2, -1 );
        if ( -1 == Counter )
        {
            perror( "fail epoll_wait" );
            return -1;
        }

        int i;
        for( i = 0; i < Counter; ++i )
        {
            if ( 0 == EpollEventArray[i].data.fd )
            {
                char strBufferStdin[100] = {0};
                read( 0, strBufferStdin, sizeof(strBufferStdin) );
                printf( "Recvfrom stdin : %s\n", strBufferStdin );
            }

            if ( FifoFd == EpollEventArray[i].data.fd )
            {
                char strBufferFifo[1024] = {0};
                read( FifoFd, strBufferFifo, sizeof(strBufferFifo) );
                printf( "Recvfrom fifo  : %s\n", strBufferFifo );
            }

        }
    }
    
    return 0;
}
